#include "uart.h"

bit busy1;
uint8_t xdata rx1_buf[RX1_MAX_LEN];
uint8_t xdata rx1_sta;
uint8_t xdata uart1_Idle;

bit busy2;
u8 xdata rx2_buf[RX2_MAX_LEN];
u8 xdata rx2_sta;
u8 xdata uart2_Idle;

char putchar(char c)
{
    Uart1SendByte(c);
    return c;
}

void Uart1Init(void)		//115200bps@33.1776MHz
{
    SCON = 0x50;		//8位数据,可变波特率
    AUXR |= 0x01;		//串口1选择定时器2为波特率发生器
    AUXR |= 0x04;		//定时器2时钟为Fosc,即1T
    T2L = 0xB8;		//设定定时初值
    T2H = 0xFF;		//设定定时初值
    AUXR |= 0x10;		//启动定时器2
}

void Uart2Init(void)		//115200bps@33.1776MHz
{
    S2CON = 0x50;		//8位数据,可变波特率
    AUXR |= 0x04;		//定时器时钟1T模式
    T2L = 0xB8;		//设置定时初始值
    T2H = 0xFF;		//设置定时初始值
    AUXR |= 0x10;		//定时器2开始计时
}

void Uart_value_Init(void)
{
    memset(rx1_buf,0,RX1_MAX_LEN);
    rx1_sta = 0;
    busy1 = 0;
    uart1_Idle = 0;
    ES = 1;

    memset(rx2_buf,0,RX2_MAX_LEN);
    rx2_sta = 0;
    busy2 = 0;
    uart2_Idle = 0;
    IE2 |= 0X01;
}

void Uart_init(void)
{
    Uart1Init();
        Uart2Init();
    Uart_value_Init();
}

void Uart1SendByte(char p)
{
    while (busy1);
    busy1 = 1;
    SBUF = p;
}

void Uart1SendStr(char *p,uint8_t len)
{
    while (len--)
    {
        Uart1SendByte(*p++);
    }
}

void Uart2SendByte(char p)
{
    while (busy2);
    busy2 = 1;
    S2BUF = p;
}

void Uart2SendStr(char *p,u8 len)
{	
    while (len--)
    {
        Uart2SendByte(*p++);
    }
}

void Uart1_handle(void)
{
    Uart1SendStr(rx1_buf,rx1_sta&0x7f);
    rx1_sta = 0;
}

void uart2_handle(void)
{
    // Uart1SendStr(rx2_buf,rx2_sta&0x7f);
    rx2_sta = 0;
}

void Uart1Isr() interrupt 4
{
    if (TI)
    {
        TI = 0;
        busy1 = 0;
    }
    if (RI)
    {
        RI = 0;
        if((rx1_sta & 0x80) == 0){
            rx1_buf[rx1_sta++] = SBUF; 
            uart1_Idle = 0x80;
        }

        // //不定长数据以 0X0D 0X0A结尾。
        // if(rx1_buf[rx1_sta-1] == 0x0d)
        // {
        // 	if(SBUF == 0X0A){
        // 		rx1_buf[rx1_sta++] = SBUF;
        // 		rx1_buf[rx1_sta] = '\0';
        // 		rx1_sta |= 0x80;
        // 	}
        // 	else
        // 	rx1_buf[rx1_sta++] = SBUF;
        // }
        // else
        // 	rx1_buf[rx1_sta++] = SBUF;
    }
}

void Uart2Isr() interrupt 8
{
    if (S2CON & 0x02)
    {
        S2CON &= ~0x02;
        busy2 = 0;
    }
    if (S2CON & 0x01)
    {
        S2CON &= ~0x01;
        if((rx2_sta & 0x80) == 0){
            rx2_buf[rx2_sta++] = S2BUF; 
            uart2_Idle = 0x80;
        }
    }
}
